package com.fyb.basic.juc.condition;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Author：MR.FANG
 * @name：ConditionDemo1
 * 锁绑定多个condition
 * 多线程之间按顺序调用，实现 A-> B -> C 三个线程启动，要求如下：
 * AA打印5次，BB打印10次，CC打印15次
 * 紧接着 AA打印5次，BB打印10次，CC打印15次
 * @Date：2025/7/2 下午3:50
 */
public class ConditionDemo1 {
    private Lock lock = new ReentrantLock();

    private Condition condition1 = lock.newCondition(); // A线程 --1
    private Condition condition2 = lock.newCondition(); // B线程 --2
    private Condition condition3 = lock.newCondition(); // C线程 --3

    private int number = 1;  // 1代表A 2代表 B  3代表C

    public void print5(){
        try{
            lock.lock();
            while (number!=1){
                try {
                    condition1.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            for (int i = 0; i < 5; i++) {
                System.out.println(Thread.currentThread().getName()+"\t AA");
            }
            number =2;
            condition2.signalAll();
        }finally {
            lock.unlock();
        }

    }

    public void print10(){
        try{
            lock.lock();
            while (number != 2){
                condition2.await();
            }
            for (int i = 0; i < 10; i++) {
                System.out.println(Thread.currentThread().getName() + "\t BB");
            }
            number=3;
            condition3.signalAll();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public void print15(){
        try{
            lock.lock();
            while (number != 3){
                condition3.await();

            }
            for (int i = 0; i < 15; i++) {
                System.out.println(Thread.currentThread().getName()+"\t CC");
            }
            number =1;
            condition1.signalAll();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }


    public static void main(String[] args) {
        ConditionDemo1 shareResource = new ConditionDemo1();

        int num = 10;

        new Thread(() -> {
            for (int i = 0; i < num; i++) {
                shareResource.print5();
            }
        }, "A").start();

        new Thread(() -> {
            for (int i = 0; i < num; i++) {
                shareResource.print10();
            }
        }, "B").start();

        new Thread(() -> {
            for (int i = 0; i < num; i++) {
                shareResource.print15();
            }
        }, "C").start();
    }
}
